# -*- coding: utf-8 -*-
# 1.加载糖尿病数据集
import matplotlib.pyplot as plt
import torch
from sklearn.datasets import load_diabetes
(data,target)=load_diabetes(return_X_y=True)
target=target.reshape(-1,1)
# 2.数据归一化
from sklearn.preprocessing import MinMaxScaler
data=MinMaxScaler().fit_transform(data)
target=MinMaxScaler().fit_transform(target)
# 3.设置序列长度，即使用过去7个时间点的数据来预测下一个时间点的数据
c=7
x=[]
y=[]
for i in range(len(data)-c):
    x.append(data[i:i+c])
    y.append(target[i+c,-1])
# 4.将输入、输出数据转换为Tensor
x=torch.tensor(x,dtype=torch.float)
y=torch.tensor(y,dtype=torch.float).reshape(-1,1)
# 5.数据划分
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(x,y,shuffle=False)
print(x_train.shape,y_train.shape)
# 6.定义线性回归模型，注意糖尿病数据集每个样本有10个特征
model=torch.nn.Linear(in_features=7*10,out_features=1)
# 7.定义损失函数和优化器
loss_fn=torch.nn.MSELoss()
optim_adam = torch.optim.Adam(model.parameters())
# 8.训练模型
model.train()
for i in range(2000):
    optim_adam.zero_grad()
    h=model(x_train.reshape(-1,7*10))
    loss=loss_fn(h,y_train)
    loss.backward()
    optim_adam.step()
    if i % 100 == 0:
        print(i,loss.item())
# 9.预测测试集结果
model.eval()
with torch.no_grad():
    h=model(x_test.reshape(-1,7*10))
    plt.plot(h)
    plt.plot(y_test)
    plt.show()
# 10.绘制结果